package pay

import (
	"context"
	"go_final/mxshop_api/order_web/global"
	orderpb "go_final/mxshop_api/order_web/proto/protofile/order"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
)

func Notify(c *gin.Context) {
	alipayInfo := global.ServerConfig.AliPayInfo
	client, err := alipay.New(alipayInfo.AppID, alipayInfo.PrivateKey, false)
	if err != nil {
		zap.S().Error("实例化支付宝client失败")
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}
	err = client.LoadAliPayPublicKey(alipayInfo.AliPublicKey)
	if err != nil {
		zap.S().Error("LoadAliPayPublicKey失败")
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	// TODO client可以做成全局变量
	noti, err := client.GetTradeNotification(c.Request)
	if err != nil {
		zap.S().Error("GetTradeNotification失败", err)
		c.JSON(http.StatusInternalServerError, gin.H{})
		return
	}

	_, err = global.OrderClient.UpdateOrderStatus(context.Background(), &orderpb.OrderStatus{
		OrderSn: noti.OutTradeNo,
		Status:  string(noti.TradeStatus),
	})

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{})
	}

	// 跟支付宝确认收到通知消息, 用插件的方法也可以, 自己返回也可以
	// alipay.AckNotification(c.Writer)
	c.String(http.StatusOK, "success")
}
